package com.jinzhi.jinzhidata.controller;

import com.alibaba.fastjson.JSONObject;
import com.jinzhi.jinzhidata.dataobject.Scene;
import com.jinzhi.jinzhidata.service.SceneService;
import com.jinzhi.jinzhidata.util.*;
import com.jinzhi.jinzhidata.vo.ResultVO;
import com.jinzhi.jinzhidata.vo.UserVO;
import com.jinzhi.jinzhidata.util.JwtUtil;
import com.jinzhi.jinzhidata.dataobject.User;
import com.jinzhi.jinzhidata.enums.ResultEnum;
import com.jinzhi.jinzhidata.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Map;

/**
 * @description
 * @date 2019-12-28 11:40
 **/
@Controller
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    SceneService sceneService;

    @GetMapping(value = "/wechatLogin")
    public String wechatLogin(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String code, String state) {
        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(state) || !"login".equals(state)) {
            return "redirect:/LoginPage";
        }
        Map<String, String> map = WXHelper.getWXOpenidAndToken(code);
        if (map == null) {
            return "redirect:/LoginPage";
        }
        String openid = map.get("openid");
        String accessToken = map.get("access_token");
        Map<String, String> userInfo = WXHelper.getWXUserInfo(accessToken, openid);
        User user = userService.userLogin(userInfo);
//        String openid = map.get("openid");
//        String access_token = map.get("access_token");
//        Map<String, String> res = WXHelper.getWXUserInfo(access_token, openid);
//        String userName = res.get("nickname");
//        String userAvatar = res.get("headimgurl");
//        String userGender = res.get("sex");
//        String userAddress = res.get("country") + " " + res.get("province") + " " + res.get("city");
//        User user = userService.selectUserByUserWeChatId(openid);
//        // 如果是第一次登录则新建用户
//        if (user == null) {
//            user = new User();
//            String uuid = UUIDUtil.getUUID();
//            user.setUserId(uuid);
//            user.setUserWechatId(openid);
//            user.setUserRole("user");
//            user.setUserBalance(new BigDecimal(0));
//        }
//        // 否则更新用户信息
//        user.setUserName(userName);
//        user.setUserAvatar(userAvatar);
//        user.setUserGender(userGender);
//        user.setUserAddress(userAddress);
//        user.setUserPassword(access_token);
//        userService.saveUser(user);

        String token = JwtUtil.sign(user.getUserId(), "WX");
        CookieUtil.addCookie(httpServletResponse, "accessToken", token);
        String targetUrl = CookieUtil.getCookieValue(httpServletRequest, "target_url");
        if (StringUtils.isEmpty(targetUrl)) {
            return "redirect:/index.html";
        }
        CookieUtil.deleteCookie(httpServletRequest, httpServletResponse, "target_url");
        return "redirect:" + targetUrl;
    }

    /**
     * 参考：
     * https://www.cnblogs.com/cmyxn/p/7803117.html
     * https://www.jianshu.com/p/7bbf53973fad
     */
    @GetMapping(value = "/webLogin")
    @ResponseBody
    public ResultVO webLogin() {
        String sceneId = UUIDUtil.getUUID();
        sceneService.insertScene(sceneId);
        String accessToken = WeChatMessageUtil.getAccessToken();
        String qrCodeUrl = WeChatMessageUtil.getQRCode(accessToken, sceneId);
        JSONObject data = new JSONObject();
        data.put("sceneId", sceneId);
        data.put("qrCodeUrl", qrCodeUrl);
        return ResultVOUtil.success(data);
    }

    @GetMapping(value = "/isWebLoginSuccess")
    @ResponseBody
    public ResultVO isWebLoginSuccess(HttpServletResponse response, String sceneId) {
        Scene scene = sceneService.selectBySceneId(sceneId);
        String token = scene.getToken();
        if (token != null) {
            CookieUtil.addCookie(response, "accessToken", token);
            return ResultVOUtil.success();
        }
        return ResultVOUtil.error(ResultEnum.NOT_LOGIN);
    }

    @GetMapping(value = "/getUserInfo")
    @ResponseBody
    public ResultVO getUserInfo(HttpServletRequest request, HttpServletResponse response) {
        String userId = JwtUtil.verifyAccessToken(request, response);
        if (userId == null) {
            return ResultVOUtil.error(ResultEnum.NOT_LOGIN);
        }
        User user = userService.selectUserByUserId(userId);
        if (user == null) {
            return ResultVOUtil.error(ResultEnum.NULL_ERROR);
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setUserPoints(user.getUserBalance().multiply(Constant.POINT_CASH_RATE));
        return ResultVOUtil.success(userVO);
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        CookieUtil.deleteCookie(request, response, "accessToken");
        return "redirect:/index.html";
    }

    @PostMapping("/updateUserName")
    @ResponseBody
    public ResultVO updateUserName(User newUser, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(newUser.getUserName())) {
            return ResultVOUtil.error(ResultEnum.USERNAME_PARAM_EMPTY);
        }
        String userId = JwtUtil.verifyAccessToken(request, response);
        if (userId == null) {
            return ResultVOUtil.error(ResultEnum.NOT_LOGIN);
        }
        User user = userService.selectUserByUserId(userId);
        if (user == null) {
            return ResultVOUtil.error(ResultEnum.NULL_ERROR);
        }
        user.setUserName(newUser.getUserName());
        userService.updateUserInfo(user);
        return ResultVOUtil.success();
    }

}
